package com.neulogistics.contrib.transfercenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.contrib.transfercenter.api.application.converter.TransferOrderPOVMConverter;
import com.neulogistics.contrib.transfercenter.api.application.converter.TransferOrderQueryPOConverter;
import com.neulogistics.contrib.transfercenter.api.application.viewmodel.TransferOrderViewModel;
import com.neulogistics.contrib.transfercenter.infrastructure.persistence.orm.po.TransferOrderPO;
import com.neulogistics.contrib.transfercenter.infrastructure.persistence.orm.service.ITransferOrderPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TransferOrderQueryService implements ITransferOrderQueryService {
    @Resource
    ITransferOrderPOService transferOrderPOService;

    @Override
    public TransferOrderViewModel getById(Long id) {
        TransferOrderPO transferOrderPO = transferOrderPOService.getById(id);
        TransferOrderViewModel transferOrderViewModel = TransferOrderPOVMConverter.POToVM(transferOrderPO);
        return transferOrderViewModel;
    }

    @Override
    public Page<TransferOrderViewModel> page(TransferOrderQuery transferOrderQuery) {
        // 取出条件
        TransferOrderPO transferOrderPO = TransferOrderQueryPOConverter.queryToPO(transferOrderQuery);
        long current = transferOrderQuery.getPageNum();
        long pageSize = transferOrderQuery.getPageSize();

        // 查询
        LambdaQueryWrapper<TransferOrderPO> queryWrapper = new LambdaQueryWrapper<>(transferOrderPO);
        Page<TransferOrderPO> page = transferOrderPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<TransferOrderViewModel> viewModelPage = new Page<>(current, pageSize);
        List<TransferOrderViewModel> viewModelList = page.getRecords().stream()
                .map(TransferOrderPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());
        return viewModelPage;
    }
}
